Error unexpected character note that you need plugins to import files that are not javascript

Issue I’ve encountered problem building typescript packages with rollup inside lerna managed monorepo. Error: lerna ERR! rollup --config ../../rollup.config.js stderr:...

Issue

I’ve encountered problem building typescript packages with rollup inside lerna managed monorepo.

Error:

lerna ERR! rollup --config ../../rollup.config.js stderr:
loaded ../../rollup.config.js with warnings
(!) Unused external imports
terser imported from external module 'rollup-plugin-terser' but never used

index.ts → dist/esm...
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
../mokui-base/component.ts (3:7)
1: const root = Symbol("root");
2: 
3: export type Component<T extends object = {}> = T & {
          ^
4:         [root]: Element;
5:         attach(element: Element): Component<T>;
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
    at error (/****/****/code/js/mokui/node_modules/rollup/dist/rollup.js:5351:30)
    at Module.error (/****/****/code/js/mokui/node_modules/rollup/dist/rollup.js:9643:9)
    at tryParse (/****/****/code/js/mokui/node_modules/rollup/dist/rollup.js:9552:16)
    at Module.setSource (/****/****/code/js/mokui/node_modules/rollup/dist/rollup.js:9868:33)
    at Promise.resolve.catch.then.then.then (/****/****/code/js/mokui/node_modules/rollup/dist/rollup.js:12148:20)


lerna ERR! rollup --config ../../rollup.config.js exited 1 in '@moki.codes/mokui-header'

Error points at “export type” tokens which is well… confusing, how come typescript doesn’t understand own constructs i am not sure.

One will be able to reproduce error by cloning repository and running yarn build:packages
@master branch.

Interestingly enough mokui-base package which defines Component builds just fine by itself, giving the error above on build only when one depend on it like i do inside the mokui-header. Reproducible by adding

if (process.env.LERNA_PACKAGE_NAME === "@moki.codes/mokui-header")
    process.exit(0);

at the top of the rollup.config.js and running yarn build:packages.

I also have another build target “dev” one can try with yarn build:dev which builds from stories/index.ts, and serves at localhost:3000. It is relevant to the question because there, mokui-header Header builds just fine depending on the mokui-base Component, Header factory is used inside index.ts and gives no errors, works as intented and provides defined behavior.

My first instinct was to opt out of the cjs build because thats the main difference between two builds(build:packages and build:dev), but that didn’t make any difference, so that leaves with the @organization/package resolution problem i guess, i am not sure… not like i know where to go from there if that’s the case. Removing export at export type Component =... inside component.ts source gets rid of the error, but of course that spawns the new error inside the mokui-header HeaderComponent complaining that Component is a value but used as type, because well… there is no Component type export to consume anymore.

So yeah, if you have any ideas where should i go from here or know exactly how i should go about building typescript package, which depends on the other sibling one please do share them.

I am sorry if i come off as rude but please don’t recommend me opting out of the custom build and use preconfigured boilerplate or something of that sort.

Thanks in advance!

Solution

In case anyone encounters the same problem, below i am providing solution:

When one attempts to build each separate package inside the monorepo, rollup attempts to resolve @organization/package-name and include it in the build. You don’t want that, so to avoid it upon building each package i am parsing package.json, extracting the dependencies field’s keys, then to check against them inside the callback one can provide inside rollup config’s external field. This will produce the desired outcome.

import json from "rollup-plugin-json";

const pkg = process.env.LERNA_PACKAGE_NAME &&
          require(`${process.env.LERNA_PACKAGE_NAME}/package.json`);

const dependencies = ({ dependencies }) => Object.keys(dependencies || {});

const pkgdependencies = dependencies(pkg);

/* exported rollup configuration */
const config = {
    /* your config goes here... */
    /* id is the source name if list of dependencies includes
     * id source name, then mark it as external,
     */
    external: id => pkgdependencies.includes(id)
};

export default config;

Answered By – Kirill Morozov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

I wrote earlier about how to use Rollup.js to bundle modules written in JavaScript but what if source files are written in TypeScript? Rollup itself can’t do transpiling so we have to instruct it to use a Typescript transpiler (typescript package).

If we have TS source file C:devgithubdemo-typescript-rollupsrcindex.ts:

function foo(s: string) {
    console.log(s);
};

foo(«Hello, world!»); 

and C:devgithubdemo-typescript-rolluprollup.config.js:

export default [{
    input: ‘src/index.ts’,
    output: {
        file: ‘dist/bundle.js’,
        format: ‘cjs’
    }
}];

…running Rollup would report an error like:

C:devgithubdemo-typescript-rollup>npx rollup -c

src/index.ts → dist/bundle.js…
[!] Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
srcindex.ts (1:14)
1: function foo(s: string) {};
                 ^
Error: Unexpected token (Note that you need plugins to import files that are not JavaScript)
    at error (C:devgithubdemo-typescript-rollupnode_modulesrollupdistrollup.js:3460:30)
    at Module.error (C:devgithubdemo-typescript-rollupnode_modulesrollupdistrollup.js:13371:9)
    at tryParse (C:devgithubdemo-typescript-rollupnode_modulesrollupdistrollup.js:13029:16)
    at Module.setSource (C:devgithubdemo-typescript-rollupnode_modulesrollupdistrollup.js:13102:33)
    at C:devgithubdemo-typescript-rollupnode_modulesrollupdistrollup.js:21768:20
    at process._tickCallback (internal/process/next_tick.js:68:7)
    at Function.Module.runMain (internal/modules/cjs/loader.js:745:11)
    at findNodeScript.then.existing (C:UserskomazecAppDataRoamingnpmnode_modulesnpmnode_moduleslibnpxindex.js:268:14)

We need to install rollup-plugin-typescript (among other packages):

C:devgithubdemo-typescript-rollup>npm install —save-dev typescript rollup rollup-plugin-typescript tslib
npm notice created a lockfile as package-lock.json. You should commit this file.
+ tslib@1.9.3
+ rollup@0.66.5
+ typescript@3.1.1
+ rollup-plugin-typescript@1.0.0
added 48 packages from 70 contributors in 13.156s

If we don’t install tslib and try to run Rollup we’ll get an error like:

$ npx rollup -c
[!] Error: Cannot find module ‘tslib/tslib.es6.js’ from ‘/home/bojan/my_app/node_modules/rollup-plugin-typescript/dist’

This is because tslib is a peer dependency of rollup-plugin-typescript:

$ npm list

├─┬ rollup-plugin-typescript@1.0.1

├── UNMET PEER DEPENDENCY tslib@*

Let’s now modify config file so it adds typescript plugin into the Rollup processing chain:

import typescript from ‘rollup-plugin-typescript’;

export default [{
    input: ‘src/index.ts’,
    output: {
        file: ‘dist/bundle.js’,
        format: ‘cjs’
    },
    plugins: [
        typescript()
      ]
}];

If we run Rollup now, it will use typescript plugin to transpile TS code to JS which will be successfully bundled:

C:devgithubdemo-typescript-rollup>npx rollup -c

src/index.ts → dist/bundle.js…
created dist/bundle.js in 71ms

To see the entire project on GitHub, go here.

References:

https://github.com/rollup/rollup-plugin-typescript
https://medium.com/@paleo.said/how-to-bundle-an-npm-package-with-typescript-and-rollup-f80e0f196189

TODO:

Try using https://www.npmjs.com/package/rollup-plugin-typescript2.

enter image description here

This is my code. I want build Vuejs components. But tip error message when building.

SCSS and PostCSS plugin are unless.

import nodeResolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'
import { babel } from '@rollup/plugin-babel'
import { terser } from 'rollup-plugin-terser'
import { eslint } from 'rollup-plugin-eslint'
import image from '@rollup/plugin-image'
import alias from '@rollup/plugin-alias'
import vuePlugin from 'rollup-plugin-vue'

const isDev = process.env.NODE_ENV !== 'production'

export default [
    {
        input: 'src/index.js',
        external: ['ms'],
        output: [
            {
                name: 'cjs',
                file: 'lib/index.js',
                format: 'cjs',
                plugins: [
                    babel({
                        exclude: 'node_modules/**', 
                        babelHelpers: 'runtime'
                        // runtimeHelpers: true 
                    })
                ]
            },
            {
                name: 'cjs',
                file: 'lib/index.min.js',
                format: 'cjs',
                plugins: [
                    terser(),
                    babel({
                        exclude: 'node_modules/**',
                        extensions: [
                            '.js', '.jsx', '.ts', '.tsx', '.vue'
                        ],
                        babelHelpers: 'runtime'
                        // runtimeHelpers: true 
                    })
                ]
            },
            {
                name: 'es',
                file: 'es/index.js',
                format: 'es'
            },
            {
                name: 'umd',
                file: 'dist/index.js',
                format: 'umd',
                plugins: [isDev && terser()]
            }
        ],
        plugins: [
            eslint({
                // fix: true,
                // throwOnError: true,
                // throwOnWarning: true,
                include: ['src/**'],
                exclude: ['node_modules/**']
            }),
            alias({
                entries: [
                    {
                        find: '@assets',
                        replacement: './src/assets'
                    }
                ]
            }),
            // scss({
            //     output: 'dist/main.css'
            // }),
            vuePlugin({
                // css: false
                // preprocessStyles: false
                // preprocessOptions: {
                //     scss: {
                //         additionalData: `@import 'src/assets/styles/varibles.scss'`,
                //         data: `@import 'src/assets/styles/mixins.scss'`
                //     }
                // }
            }),

            // postcss({
            //     use: {
            //         sass: {
            //             data: [
            //                 `@import 'src/assets/styles/varibles.scss'`,
            //                 `@import 'src/assets/styles/mixins.scss'`
            //             ]
            //         }
            //     }
            // }),
            image(),
            nodeResolve()
            commonjs(),
        ]
    }
]

Discussion on: How to Build A React TS Tailwind Design System


Collapse

Expand


nefertiter profile image

Hi Yoav,
It’s super useful the content, however I was having this issue when trying to run the yarn build
Error: Unexpected character '@' (Note that you need plugins to import files that are not JavaScript)
.../src/index.css:1:0
1: @tailwind base;
^
2: @tailwind components;
3: @tailwind utilities;

Any idea how to prevent the @ error ?
I’m currently using the tsdx + tailwind + rollup-plugin-postcss + chromatic [ just installed]


Collapse

Expand


hamatoyogi profile image

Yoav Ganbar

Developer Experience @ Builder.io, Software Architect, Full Stack Web developer, and web connoisseur.

  • Email

  • Location

    127.0.0.1

  • Work

    Developer Experience @ Builder.io

  • Joined

    Sep 28, 2019

May 11 ’21

  • Copy link

Hi Marcos,
Glad you liked the post!
From the looks of it, seems like postCSS is not configured properly. But this is a shot in the dark without seeing the actual code. Are you getting this from trying to run the related posts’ repo or your own?


Collapse

Expand


nefertiter profile image

I have started all over again

  1. Tsdx setup react-storybook
  2. Install tailwind
  3. Created the postcss.config.js
  4. Tailwind init
  5. Add yarn add -D rollup-plugin-postcss
  6. Added the tailwind css file to index
  7. Yarn build worked!

So im sorry for taking your time! I’m really not sure what could have be missing, likely something my tailwind config.

PS build took several minutes that was a bit unexpected
again thank you for the guide!

hamatoyogi profile image

Yoav Ganbar

Developer Experience @ Builder.io, Software Architect, Full Stack Web developer, and web connoisseur.

  • Email

  • Location

    127.0.0.1

  • Work

    Developer Experience @ Builder.io

  • Joined

    Sep 28, 2019

May 14 ’21

  • Copy link

Happy it worked out!
Go build something awesome! 🙂

Понравилась статья? Поделить с друзьями:
  • Error undefined при печати
  • Error undefined variable sass
  • Error undefined variable in expression clanids
  • Error undefined symbol wsregistercustomimagelistresolution
  • Error undefined reference to vtable